/*
 * @Description:
 * @FilePath: /glm_h5wxgzh/utils/request.js
 */
import store from "@/store";
import config from "@/config";
import cache from "@/plugins/cache";
import { getToken } from "@/utils/auth";
import errorCode from "@/utils/errorCode";
import { toast, showConfirm, tansParams } from "@/utils/common";

let timeout = 30000;
const baseUrl = config.baseUrl;
const sysFeedRec = config.sysFeedRec;

const request = (config) => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  // 是否需要防止数据重复提交
  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
  config.header = config.headers || {};
  if (getToken() && !isToken) {
    // 让每个请求携带自定义token 请根据实际情况自行修改
    config.header["Authorization"] = "Bearer " + getToken();
  }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + "?" + tansParams(config.params);
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  if (
    !isRepeatSubmit &&
    (config.method === "post" || config.method === "put")
  ) {
    const requestObj = {
      url: config.url,
      data:
        typeof config.data === "object"
          ? JSON.stringify(config.data)
          : config.data,
      time: new Date().getTime(),
    };
    const requestSize = Object.keys(JSON.stringify(requestObj)).length; // 请求数据大小
    const limitSize = 5 * 1024 * 1024; // 限制存放数据5M
    if (requestSize >= limitSize) {
      return console.warn(
        `[${config.url}]: ` +
          "请求数据大小超出允许的5M限制，无法进行防重复提交验证。"
      );
    }
    // const sessionObj = cache.session.getJSON("sessionObj");
    // if (sessionObj === undefined || sessionObj === null || sessionObj === "") {
    //   cache.session.setJSON("sessionObj", requestObj);
    // } else {
    //   const s_url = sessionObj.url; // 请求地址
    //   const s_data = sessionObj.data; // 请求数据
    //   const s_time = sessionObj.time; // 请求时间
    //   const interval = 1000; // 间隔时间(ms)，小于此时间视为重复提交
    //   if (
    //     s_data === requestObj.data &&
    //     requestObj.time - s_time < interval &&
    //     s_url === requestObj.url
    //   ) {
    //     const message = "数据正在处理，请勿重复提交";
    //     return console.warn(`[${s_url}]: ` + message);
    //     // return Promise.reject(new Error(message));
    //   } else {
    //     cache.session.setJSON("sessionObj", requestObj);
    //   }
    // }
  }
  return new Promise((resolve, reject) => {
    uni
      .request({
        method: config.method || "get",
        timeout: config.timeout || timeout,
        url: config.baseUrl || baseUrl + config.url,
        data: config.data,
        header: config.header,
        dataType: "json",
      })
      .then((response) => {
        let [error, res] = response;
        if (error) {
          toast("后端接口连接异常");
          reject("后端接口连接异常");
          return;
        }
        const code = res.data.code || 200;
        const msg = errorCode[code] || res.data.msg || errorCode["default"];
        if (code === 401) {
          // showConfirm(
          //   "登录状态已过期，您可以继续留在该页面，或者重新登录?"
          // ).then((res) => {
          //   if (res.confirm) {
          //     store.dispatch("LogOut").then((res) => {
          //       uni.reLaunch({ url: "/pages/login" });
          //     });
          //   }
          // });
		  uni.navigateTo({
		  	url:"/pages/prejudgment/prejudgment"
		  })
          reject("无效的会话，或者会话已过期，请重新登录。");
        } else if (code === 500) {
          toast(msg);
          reject(code);
        } else if (code !== 200) {
          toast(msg);
          reject(code);
        }
        resolve(res.data);
      })
      .catch((error) => {
        let { message } = error;
        if (message === "Network Error") {
          message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
          message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
          message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        toast(message);
        reject(error);
      });
  });
};

export default request;
